#!/usr/bin/env python

import tornado.database
import tornado.httpserver
import tornado.ioloop
import tornado.web

from settings import *

import handlers.site
import handlers.admin
import ui


class URLSpec(tornado.web.URLSpec):
    def reverse(self, *args):
        assert self._path is not None, \
            "Cannot reverse url regex " + self.regex.pattern
        assert len(args) == self._group_count, "required number of arguments "\
            "not found"
        if not len(args):
            return self._path
        return self._path % tuple([a.encode('utf-8') for a in args])


class Application(tornado.web.Application):
	def reverse_url(self, name, *args):
		url = tornado.web.Application.reverse_url(self, name, *args)
		return url.strip('?')
	
	def __init__(self):
		app_handlers = [
			('admin', r'/admin', handlers.admin.AdminHandler),
			('signin', r'/admin/signin', handlers.SignInHandler),
			('signout', r'/admin/signout', handlers.SignOutHandler),
			('prefs', r'/admin/prefs', handlers.admin.PrefsHandler),
			('clear_links', r'/admin/prefs/clear_links', handlers.admin.ClearLinksHandler),
			('create', r'/admin/create', handlers.admin.CreateHandler),
			('edit', r'/admin/edit/([^/]+)', handlers.admin.EditHandler),
			('upload', r'/admin/upload', handlers.admin.UploadHandler),
			('delete_upload', r'/admin/delete_upload', handlers.admin.DeleteUploadHandler),
			('delete', r'/admin/delete', handlers.admin.DeleteHandler),
			('order', r'/admin/order', handlers.admin.OrderHandler),
			('hide', r'/admin/hide', handlers.admin.HideHandler),
            ('base_category', r'/base/category', handlers.site.BaseCategoryHandler),
            ('add_base_category', r'/base/category/add', handlers.site.AddBaseCategoryHandler),
            ('delete_base_category', r'/base/category/delete', handlers.site.DeleteBaseCategoryHandler),
            ('base_item', r'/base/item', handlers.site.BaseItemHandler),
            ('add_base_item', r'/base/item/add', handlers.site.AddBaseItemHandler),
            ('delete_base_item', r'/base/item/delete', handlers.site.DeleteBaseItemHandler),
            ('line', r'/line', handlers.site.LineHandler),
            ('add_line', r'/line/add', handlers.site.AddLineHandler),
            ('delete_line', r'/line/delete', handlers.site.DeleteLineHandler),
			('finance', r'/finance', handlers.site.FinanceHandler),
            ('add_finance', r'/finance/add', handlers.site.AddFinanceHandler),
           ('page', r'/([^/]+)?', handlers.site.PageHandler)
		]
		
		app_handlers = [URLSpec(pattern, handler, dict(page_name=name), name=name) \
			for name, pattern, handler in app_handlers]
		
		app_settings = dict(
			xsrf_cookies=True,
			login_url='/admin/signin',
			template_path=os.path.join(os.path.dirname(__file__), 'templates'),
			static_path=os.path.join(os.path.dirname(__file__), 'static'),
			upload_path='uploads',
			ui_modules=ui,
			autoescape=None,
			debug=True
		)
		
		app_settings.update(settings)
		
		tornado.web.Application.__init__(self, app_handlers, **app_settings)
		
		self.db = tornado.database.Connection(
			host=options.mysql_host, database=options.mysql_database,
			user=options.mysql_user, password=options.mysql_password)


def main():
	tornado.options.parse_command_line()
	http_server = tornado.httpserver.HTTPServer(Application())
	http_server.listen(options.port)
	tornado.ioloop.IOLoop.instance().start()


if __name__ == "__main__":
	main()
